/*
 * @Author: wuzhen
 * @Date: 2020-01-15 19:41:33
 * @LastEditors: wuzhen
 * @LastEditTime: 2020-04-17 17:20:47
 * @Description: 头部注释
 */
import store from "@/store";
import router from "@/router";
export default class IMWebSocket {
  constructor() {
    this.socketOpen = false;
    this.timer = 0;
  }
  // 创建socket连接
  createSocket() {
    if ("WebSocket" in window) {
      if (this.socketOpen) return;
      this.ws = new WebSocket(
        `wss://web.butter.im/ws/wsim?jsessionId=${store.state.chat.jsessionId}&UNF=${store.state.chat.unf}&LOCAL=${store.state.system.local}&CONNECTOR=WEB`
      );
      this.onOpen();
      this.onMessage();
      this.onError();
      this.onClose();
    } else {
      console.log("当前浏览器不支持");
    }
  }
  // 连接成功
  onOpen() {
    this.ws.onopen = () => {
      this.socketOpen = true;
      this.timer = 0;
      console.log("连接成功");
    };
  }
  // 连接失败
  onError() {
    this.ws.onerror = () => {
      this.socketOpen = false;
      console.log("连接失败");
    };
  }
  // 接收数据
  onMessage() {
    this.ws.onmessage = data => {
      const result = JSON.parse(data.data);
      window.dispatchEvent(
        new CustomEvent("onmessageWS", {
          detail: result
        })
      );
    };
  }
  // 连接关闭
  async onClose() {
    this.ws.onclose = async () => {
      this.socketOpen = false;
      if (this.timer === 20) {
        this.timer = 0;
        await store.dispatch("onClearStroage");
        router.replace("/");
      } else {
        setTimeout(() => {
          if (router.app._route.path !== "/") {
            this.timer++;
            this.createSocket();
          }
        }, 1000);
      }
    };
  }
  // 发送消息
  sendMsg(msg, http_seqno = new Date().getTime()) {
    const data = JSON.stringify({
      message: {
        module: "message",
        action: "onMessage",
        http_seqno: http_seqno,
        params: `bean=${msg}`
      }
    });
    this.ws.send(data);
  }
  closeScoket() {
    this.ws.close();
  }
}
